//
//  CJBannerGMAdapter.m
//  CJModileGMAdapter
//
//  Created by shanghailingye on 2024/4/24.
//

#import "CJBannerToBidAdapter.h"


@interface CJBannerToBidAdapter()<CJNativeAdDelegate>

@property (nonatomic, weak) id<AWMCustomBannerAdapterBridge> bridge;
@property (nonatomic, strong) CJNativeAd *nativeAd;
@property (nonatomic, strong) UIView *bannerView;
// 是否是bidding
@property (nonatomic, assign) BOOL isBidding;

@end
@implementation CJBannerToBidAdapter

- (instancetype)initWithBridge:(id<AWMCustomBannerAdapterBridge>)bridge {
    self = [super init];
    if (self) {
       _bridge = bridge;
    }
    return self;
}

- (void)loadAdWithPlacementId:(NSString *)placementId parameter:(AWMParameter *)parameter {
    self.isBidding = parameter.isHeaderBidding;
    CGFloat adWidth = [UIScreen mainScreen].bounds.size.width;
    if ([[self.bridge adRequest].options valueForKey:@"ad_width"]) {
        adWidth = [[[self.bridge adRequest].options valueForKey:@"ad_width"] floatValue];
    }
    CGSize adSize = CGSizeMake(adWidth, 0);
    self.nativeAd = [[CJNativeAd alloc] initWithSlotId:placementId size:adSize rootViewController:[CJCommonToBidFunc currentRootController]];
    self.nativeAd.delegate = self;
    [self.nativeAd loadAdData:1];
}

- (BOOL)mediatedAdStatus {
    return true;
}


#pragma mark CJNativeAdDelegate
- (void)nativeExpressAdDidLoad:(nonnull NSArray *)nativeExpressViews {
    NSInteger cpm = [self.nativeAd getECpm];
    NSDictionary *ext = @{
        AWMMediaAdLoadingExtECPM : cpm ? [NSString stringWithFormat:@"%ld", cpm] : @"0",
    };
    if (nativeExpressViews.count > 0 && [nativeExpressViews.firstObject isKindOfClass:[UIView class]]) {
        self.bannerView = nativeExpressViews.firstObject;
        if (self.isBidding) {
            [self.bridge bannerAd:self didAdServerResponse:nativeExpressViews.firstObject ext:ext];
        }
        [self.bridge bannerAd:self didLoad:nativeExpressViews.firstObject];
    }
}

- (void)nativeExpressAdDidRender:(nonnull id)nativeExpressView {
    
}

- (void)nativeExpressAdLoadFailed:(nonnull id)nativeExpressAd error:(nonnull NSError *)error {
    [self.bridge bannerAd:self didLoadFailWithError:error ext:nil];
}

- (void)nativeExpressAdOnClicked:(nonnull id)nativeExpressView {
    [self.bridge bannerAdDidClick:self bannerView: self.bannerView];
}

- (void)nativeExpressAdOnClosed:(nonnull id)nativeExpressView {
    [self.bridge bannerAdDidClosed:self bannerView:self.bannerView];
}

- (void)nativeExpressAdOnShow:(nonnull id)nativeExpressView {
    [self.bridge bannerAdDidBecomeVisible:self bannerView:self.bannerView];
}

@end
